package com.example.android.activities

import android.app.Activity
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.android.R
import com.example.android.extensions.Alert
import com.example.android.extensions.AlertBar
import com.example.android.extensions.AlertDialog
import com.example.android.extensions.Services
import com.example.android.utils.models.MyResult
import com.royrodriguez.transitionbutton.TransitionButton
import kotlinx.android.synthetic.main.fragment_select_bed_finish.view.*
import kotlinx.coroutines.*

/**
 * @ClassName UpdatePasswordActivity
 * @Author Ryan Kamanri
 * @Date 2022/6/9
 * @Description
 **/
class UpdatePasswordActivity : AppCompatActivity() {
    companion object {
        val UPDATE_SUCCESS = 200


    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_update_password)

        var isValidAccount = false
        var isValidUserName = false
        var isValidUserCredit = false
        var isValidNewPassword = false
        var isValidDoubleNewPassword = false

        var account = ""
        var userName = ""
        var userCredit = ""
        var password = ""

        CheckInput(this, R.id.update_password_account,
            R.id.update_password_account_hint,
            "请输入账号!") {input, _ ->
            isValidAccount = true
            account = input
        }

        CheckInput(this, R.id.update_password_user_name,
            R.id.update_password_user_name_hint,
            "请输入姓名!") {input, _ ->
            isValidUserName = true
            userName = input
        }

        CheckInput(this, R.id.update_password_user_credit,
            R.id.update_password_user_credit_hint,
            "请输入身份证号!") { input, hint ->

            if(input.length != 18) {
                hint.text = "身份证号码为18位"
                return@CheckInput
            }
            isValidUserCredit = true
            userCredit = input
        }

        CheckInput(this, R.id.update_password_new_password,
            R.id.update_password_new_password_hint,
            "请输入新密码!") { input, hint ->
            if(input.length < 6 || input.length > 14) {
                hint.text = "密码长度为6-14位"
                return@CheckInput
            }
            if(!Regex("^\\w*$").matches(input)) {
                hint.text = "密码由字母或数字组成"
                return@CheckInput
            }
            password = input
            isValidNewPassword = true
        }

        CheckInput(this, R.id.update_password_double_new_password,
            R.id.update_password_double_new_password_hint,
            "请输入确认密码!") { input, hint ->
            if(password != input) {
                hint.text = "两次密码不一致"
                return@CheckInput
            }
            isValidDoubleNewPassword = true
        }



        findViewById<Button>(R.id.update_password_button).setOnClickListener {
            // 移除焦点
            findViewById<EditText>(R.id.update_password_account).clearFocus()
            if(!isValidAccount) {
                Alert("请检查你的 账号 输入是否合法")
                return@setOnClickListener
            }
            findViewById<EditText>(R.id.update_password_user_name).clearFocus()
            if(!isValidUserName) {
                Alert("请检查你的 姓名 输入是否合法")
                return@setOnClickListener
            }
            findViewById<EditText>(R.id.update_password_user_credit).clearFocus()
            if(!isValidUserCredit) {
                Alert("请检查你的 身份证号 输入是否合法")
                return@setOnClickListener
            }
            findViewById<EditText>(R.id.update_password_new_password).clearFocus()
            if(!isValidNewPassword) {
                Alert("请检查你的 新密码 输入是否合法")
                return@setOnClickListener
            }
            findViewById<EditText>(R.id.update_password_double_new_password).clearFocus()
            if(!isValidDoubleNewPassword) {
                Alert("请检查你的 确认密码 输入是否合法")
                return@setOnClickListener
            }

            AlertDialog {
                it.SetContent("确认要修改密码吗?")
                    .SetOnSureButton {
                        it.dismiss()
                        UpdatePassword(account, userName, userCredit, password)
                    }.SetOnCancelButton {
                        it.dismiss()
                    }
            }
        }
    }

    private fun UpdatePassword(account: String, userName: String, userCredit: String, password: String) {
        lifecycleScope.launch(Dispatchers.Main) {
            runCatching {
                val result = Services.UpdatePasswordService.UpdatePassword(account, userName, userCredit, password)
                when(result.Code) {
                    MyResult.OK -> {
                        setResult(UPDATE_SUCCESS)
                        finish()
                    }
                    else -> {
                        Alert("修改失败了(${result.Message})")
                        Log.i(toString(), result.Message)
                    }
                }

            }.onFailure {
                Log.e(toString(), "Failure To Update Password Caused By: ${it.message}")
                it.printStackTrace()
                Alert("出现错误(${it.message!!})")

            }

        }
    }

    private fun CheckInput(
        activity: Activity,
        editTextResId: Int,
        hintResId: Int,
        emptyHint: String,
        onInputChangeListener: (String, TextView) -> Unit = { _, _ -> }
    ) {

        val editText = activity.findViewById<EditText>(editTextResId)
        val hintText = activity.findViewById<TextView>(hintResId)

        editText.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && editText.text.toString() == "") {
                hintText.text = emptyHint
            }
            else {
                hintText.text = ""
                if(!hasFocus) {
                    onInputChangeListener(editText.text.toString(), hintText)
                }
            }

        }

    }


}

